package com.zzyl.nursing.service.impl;
import java.util.*;
import java.time.LocalDateTime;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.job.vo.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据上报Service业务层处理
 *
 * @author syl
 * @date 2025-06-02
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据上报
     *
     * @param id 设备数据上报主键
     * @return 设备数据上报
     */
    @Override
    public synchronized DeviceData selectDeviceDataById(Long id)
    {
            return getById(id);
    }

    /**
     * 查询设备数据上报列表
     *
     * @param deviceData 设备数据上报
     * @return 设备数据上报
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据上报
     *
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData)?1:0;
    }

    /**
     * 修改设备数据上报
     *
     * @param deviceData 设备数据上报
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData)?1:0;
    }

    /**
     * 批量删除设备数据上报
     *
     * @param ids 需要删除的设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备数据上报信息
     *
     * @param id 设备数据上报主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private DeviceMapper deviceMapper;


    @Override
    public void batchInsertFromContentStr(String contentStr) {
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        String deviceId = jsonObject.getByPath("notify_data.header.device_id",String.class);
        if(StrUtil.isEmpty(deviceId)){
            return;
        }
        // 查询设备
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,deviceId);
        Device device = deviceMapper.selectOne(queryWrapper);
        if(ObjectUtil.isNull(device)){
            return;
        }

        // 准备保存数据
        IotMsgService iotMsgService = jsonObject.getByPath("notify_data.body.services[0]", IotMsgService.class);


        String eventTimeStr = iotMsgService.getEventTime();//20250601 T 08 24 34 Z
        LocalDateTime eventTimeUTC = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUTC);

        Map<String, Object> properties = iotMsgService.getProperties();

        // 准备一个集合用来批量保存
        List<DeviceData> list = new ArrayList<>();

        properties.forEach((key,value)->{    // "CurrentHumidity": 38,
            DeviceData deviceData =  BeanUtil.toBean(device, DeviceData.class);
            // 但是注意id也拷贝了 作为新增id不需要
            deviceData.setId(null);
            deviceData.setFunctionId(key);
            deviceData.setDataValue(value+"");
            deviceData.setAlarmTime(eventTime);
            list.add(deviceData);
        });

        try {
            saveBatch(list);

            redisTemplate.boundHashOps(CacheConstants.IOT_DEVICE_LAST_DATA).put(deviceId,JSONUtil.toJsonStr(list));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


}
